import { config } from './config.js';

// 获取域名列表和账号信息
async function fetchDomains() {
    try {
        const response = await fetch(`${config.API_BASE_URL}/api/passwords`, {
            headers: {
                'Authorization': `Bearer ${localStorage.getItem('token')}`
            }
        });

        const result = await response.json();
        
        if (!result.ok) {
            throw new Error(result.error || '获取密码列表失败');
        }

        const domainList = document.getElementById('domain-list');
        domainList.innerHTML = '';

        // 添加加载动画
        for (let i = 0; i < 6; i++) {
            domainList.innerHTML += '<div class="loading-skeleton"></div>';
        }

        // 延迟100ms以显示加载动画
        await new Promise(resolve => setTimeout(resolve, 100));
        
        domainList.innerHTML = '';

        // 更新密码数量
        const passwordCount = result.data.results.length;
        updatePasswordCount(passwordCount);

        result.data.results.forEach((item, index) => {
            const li = document.createElement('div');
            li.className = 'domain-item';
            // 添加延迟动画
            li.style.animationDelay = `${index * 0.1}s`;
            
            const date = new Date(item.created_at);
            const formattedDate = date.toLocaleDateString('zh-CN', {
                year: 'numeric',
                month: 'long',
                day: 'numeric'
            });

            li.innerHTML = `
                <div class="domain-info">
                    <div class="domain-url">${item.url}</div>
                    <div class="domain-meta">
                        <div class="domain-username">${item.username}</div>
                        <div class="domain-date">${formattedDate}</div>
                    </div>
                </div>
            `;
            li.addEventListener('click', () => viewPassword(item));
            domainList.appendChild(li);
        });
    } catch (error) {
        console.error('获取密码列表失败:', error.message);
        alert('获取密码列表失败，请重试');
    }
}

// 获取密码数量
async function fetchPasswordCount() {
    try {
        const response = await fetch(`${config.API_BASE_URL}/api/passwords/count`, {
            headers: {
                'Authorization': `Bearer ${localStorage.getItem('token')}`
            }
        });

        const result = await response.json();
        
        if (!result.ok) {
            throw new Error(result.error || '获取密码数量失败');
        }

        updatePasswordCount(result.data.count);
    } catch (error) {
        console.error('获取密码数量失败:', error);
    }
}

// 更新密码数量显示
function updatePasswordCount(count) {
    const passwordCount = document.getElementById('passwordCount');
    if (passwordCount) {
        passwordCount.textContent = count;
    }
}

// 搜索密码
async function searchPasswords() {
    const searchTerm = document.getElementById('search-input').value.toLowerCase();
    const domainItems = document.querySelectorAll('.domain-item');
    
    domainItems.forEach(item => {
        const text = item.textContent.toLowerCase();
        if (text.includes(searchTerm)) {
            item.style.display = 'flex';
        } else {
            item.style.display = 'none';
        }
    });
}

// 生成随机密码
function generatePassword(length = 16) {
    const charset = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%^&*()_+-=[]{}|;:,.<>?';
    let password = '';
    for (let i = 0; i < length; i++) {
        const randomIndex = Math.floor(Math.random() * charset.length);
        password += charset[randomIndex];
    }
    return password;
}

// 设置添加密码模态框的事件处理器
function setupAddModalHandlers() {
    const modal = document.getElementById('add-password-modal');
    const form = document.getElementById('add-password-form');
    const passwordInput = document.getElementById('add-password');
    const togglePasswordBtn = modal.querySelector('.toggle-password');
    const generatePasswordBtn = modal.querySelector('.generate-password');
    const cancelBtn = document.getElementById('add-cancel-btn');
    const closeBtn = modal.querySelector('.close');

    // 显示/隐藏密码
    togglePasswordBtn.onclick = () => {
        const type = passwordInput.type === 'password' ? 'text' : 'password';
        passwordInput.type = type;
        togglePasswordBtn.querySelector('.icon').textContent = type === 'password' ? '👁️' : '👁️‍🗨️';
    };

    // 生成随机密码
    generatePasswordBtn.onclick = () => {
        const password = generatePassword();
        passwordInput.type = 'text'; // 显示生成的密码
        passwordInput.value = password;
        togglePasswordBtn.querySelector('.icon').textContent = '👁️‍🗨️';
    };

    // 取消按钮
    cancelBtn.onclick = () => {
        closeModal('add-password-modal');
        form.reset();
    };

    // 关闭按钮
    closeBtn.onclick = () => {
        closeModal('add-password-modal');
        form.reset();
    };

    // 点击模态框外部关闭
    modal.onclick = (event) => {
        if (event.target === modal) {
            closeModal('add-password-modal');
            form.reset();
        }
    };

    // 表单提交
    form.onsubmit = async (event) => {
        event.preventDefault();
        
        try {
            const url = document.getElementById('add-url').value.trim();
            const username = document.getElementById('add-username').value.trim();
            const password = document.getElementById('add-password').value;
            const note = document.getElementById('add-note').value.trim();

            // 验证必填字段
            if (!url || !username || !password) {
                throw new Error('请填写所有必填字段');
            }         

            // 发送创建密码请求
            const response = await fetch(`${config.API_BASE_URL}/api/passwords`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'Authorization': `Bearer ${localStorage.getItem('token')}`
                },
                body: JSON.stringify({
                    url,
                    username,
                    password,
                    note
                })
            });

            if (!response.ok) {
                const error = await response.json();
                if(error.code === 'KEY_TIMEOUT'){
                    alert('密钥超时，请重新登录');
                    handleLogout();
                }
                throw new Error(error.message || '创建密码失败');
            }

            // 关闭模态框并重置表单
            closeModal('add-password-modal');
            form.reset();
            
            // 刷新密码列表和数量
            fetchDomains();
            fetchPasswordCount();
            
            alert('密码创建成功');
        } catch (error) {
            console.error('创建密码失败:', error);
            alert(error.message || '创建密码失败，请重试');
        }
    };
}

// 查看密码
async function viewPassword(item) {
    try {
        // 获取密码详情
        const response = await fetch(`${config.API_BASE_URL}/api/passwords/${item.id}/detail`, {
            headers: {
                'Authorization': `Bearer ${localStorage.getItem('token')}`
            }
        });

        if (!response.ok) {
            const error = await response.json();
            throw new Error(error.message || error.error || '获取密码详情失败');
        }

        const result = await response.json();
        const passwordData = result.data;

        // 保存当前查看的密码ID
        window.currentPasswordId = item.id;

        // 填充表单
        document.getElementById('view-url').value = passwordData.url;
        document.getElementById('view-username').value = passwordData.username;
        document.getElementById('view-password').value = passwordData.password;
        document.getElementById('view-note').value = passwordData.note || '';
        
        // 打开模态框
        openModal('view-password-modal');

        // 绑定事件处理器
        setupViewModalHandlers();
    } catch (error) {
        console.error('查看密码失败:', error);
        alert(error.message || '查看密码失败，请重试');
    }
}

// 设置查看模态框的事件处理器
function setupViewModalHandlers() {
    const modal = document.getElementById('view-password-modal');
    const passwordInput = document.getElementById('view-password');
    const togglePasswordBtn = modal.querySelector('.toggle-password');
    const copyPasswordBtn = modal.querySelector('.copy-password');
    const deleteBtn = document.getElementById('delete-password-btn');
    const editBtn = document.getElementById('edit-password-btn');
    const cancelBtn = document.getElementById('view-cancel-btn');
    const closeBtn = modal.querySelector('.close');

    // 显示/隐藏密码
    togglePasswordBtn.onclick = () => {
        const type = passwordInput.type === 'password' ? 'text' : 'password';
        passwordInput.type = type;
        togglePasswordBtn.querySelector('.icon').textContent = type === 'password' ? '👁️' : '👁️‍🗨️';
    };

    // 复制密码
    copyPasswordBtn.onclick = async () => {
        try {
            await navigator.clipboard.writeText(passwordInput.value);
            const icon = copyPasswordBtn.querySelector('.icon');
            icon.textContent = '✅';
            setTimeout(() => {
                icon.textContent = '📋';
            }, 1000);
        } catch (err) {
            alert('复制失败，请手动复制');
        }
    };

    // 删除密码
    deleteBtn.onclick = async () => {
        if (!window.currentPasswordId) return;
        
        if (!confirm('确定要删除这个密码吗？此操作不可恢复。')) {
            return;
        }

        try {
            const response = await fetch(`${config.API_BASE_URL}/api/passwords/${window.currentPasswordId}`, {
                method: 'DELETE',
                headers: {
                    'Authorization': `Bearer ${localStorage.getItem('token')}`
                }
            });

            if (!response.ok) {
                const error = await response.json();
                throw new Error(error.message || error.error || '删除密码失败');
            }

            closeModal('view-password-modal');
            fetchDomains(); // 刷新列表
            fetchPasswordCount(); // 更新密码数量
            alert('密码已删除');
        } catch (error) {
            console.error('删除密码失败:', error);
            alert(error.message || '删除密码失败，请重试');
        }
    };

    // 编辑密码
    editBtn.onclick = () => {
        editPassword();
    };

    // 取消按钮
    cancelBtn.onclick = () => {
        closeModal('view-password-modal');
    };

    // 关闭按钮（x）
    closeBtn.onclick = () => {
        closeModal('view-password-modal');
    };

    // 点击模态框外部关闭
    modal.onclick = (event) => {
        if (event.target === modal) {
            closeModal('view-password-modal');
        }
    };
}

// 编辑密码
function editPassword() {
    const url = document.getElementById('view-url').value;
    const username = document.getElementById('view-username').value;
    const password = document.getElementById('view-password').value;
    const note = document.getElementById('view-note').value;

    document.getElementById('edit-url').value = url;
    document.getElementById('edit-username').value = username;
    document.getElementById('edit-password').value = password;
    document.getElementById('edit-note').value = note;

    closeModal('view-password-modal');
    openModal('edit-password-modal');
    setupEditModalHandlers();
}

// 设置编辑模态框的事件处理器
function setupEditModalHandlers() {
    const modal = document.getElementById('edit-password-modal');
    const form = document.getElementById('edit-password-form');
    const passwordInput = document.getElementById('edit-password');
    const togglePasswordBtn = modal.querySelector('.toggle-password');
    const closeBtn = modal.querySelector('.close');
    const cancelBtn = document.getElementById('edit-cancel-btn');

    // 显示/隐藏密码
    togglePasswordBtn.onclick = () => {
        const type = passwordInput.type === 'password' ? 'text' : 'password';
        passwordInput.type = type;
        togglePasswordBtn.querySelector('.icon').textContent = type === 'password' ? '👁️' : '👁️‍🗨️';
    };

    // 关闭按钮（x）
    closeBtn.onclick = () => {
        closeModal('edit-password-modal');
    };

    // 取消按钮
    cancelBtn.onclick = () => {
        closeModal('edit-password-modal');
    };

    // 点击模态框外部关闭
    modal.onclick = (event) => {
        if (event.target === modal) {
            closeModal('edit-password-modal');
        }
    };

    // 表单提交
    form.onsubmit = async (event) => {
        event.preventDefault();
        
        try {
            const url = document.getElementById('edit-url').value.trim();
            const username = document.getElementById('edit-username').value.trim();
            const password = document.getElementById('edit-password').value;
            const note = document.getElementById('edit-note').value.trim();

            // 验证必填字段
            if (!url || !username || !password) {
                throw new Error('请填写所有必填字段');
            }         

            const response = await fetch(`${config.API_BASE_URL}/api/passwords/${window.currentPasswordId}`, {
                method: 'PUT',
                headers: {
                    'Content-Type': 'application/json',
                    'Authorization': `Bearer ${localStorage.getItem('token')}`
                },
                body: JSON.stringify({
                    url,
                    username,
                    password,
                    note
                })
            });

            if (!response.ok) {
                const result = await response.json();
                if(result.code === 'KEY_TIMEOUT'){
                    alert('密钥超时，请重新登录');
                    handleLogout();
                    return;
                }
                throw new Error(result.message || '更新密码失败');
            }

            alert('密码更新成功');
            closeModal('edit-password-modal');
            fetchDomains(); // 刷新列表
        } catch (error) {
            console.error('更新密码失败:', error);
            alert(error.message || '更新密码失败，请重试');
        }
    };
}

// 模态框操作
function openModal(modalId) {
    document.getElementById(modalId).style.display = 'block';
}

function closeModal(modalId) {
    document.getElementById(modalId).style.display = 'none';
}

// 返回主页
function handleBackToDashboard() {
    window.location.href = 'dashboard.html';
}

// 退出登录
function handleLogout() {
    localStorage.clear();
    window.location.href = 'index.html';
}

// 初始化
document.addEventListener('DOMContentLoaded', () => {
    fetchDomains();
    fetchPasswordCount();  // 添加获取密码数量的调用
    
    // 搜索功能
    document.getElementById('search-input').addEventListener('input', searchPasswords);
    
    // 添加密码按钮
    document.getElementById('addPasswordBtn').addEventListener('click', () => {
        openModal('add-password-modal');
        setupAddModalHandlers();
    });
    
    // 导航按钮
    document.getElementById('backToDashboard').addEventListener('click', handleBackToDashboard);
    document.getElementById('logoutBtn').addEventListener('click', handleLogout);
});


